import { computed, ref } from "vue";

export function useCountdown() {
  let timer = null;
  const remaining = ref(0);
  const veryCodeBtnTxt = computed(() => 0 < remaining.value ? `${remaining.value}秒后重新获取` : '获取验证码');

  function countdown() {
    remaining.value = 60;
    timer && clearInterval(timer);
    timer = setInterval(() => {
      if (remaining.value <= 0) {
        clearInterval(timer);
        timer = null;
        return;
      }

      --remaining.value;
    }, 1000);
  }

  return {
    remaining,
    veryCodeBtnTxt,
    countdown,
  };
}
